CommutersConnectNewReport = new function() {


  //When the page is loaded, we need to change the form action back to
  //something that works for the file uploads.  Note that the form itself is
  //handled via the ajax functionality of Lift.
  this.setup = function() {
    var uuid = $("[name=ajaxUploadId]")[0].value;
    $("form").attr('action', 'newReport/attachImage/'+uuid);

    //Once a file is uploaded, we will copy any geocode information from the
    //upload result into the location field.  In doing this, we make sure not
    //to geocode the new location that we enter, as we already have the lat
    //and lng associated with it so we will just update here.  (Also, if you
    //upload multiple files, we only look at the data associated with the
    //first one.)
    $('#newReport').fileupload( {
      form: "newReport",
      autoUpload: true
    })
    .bind("fileuploaddone", function(e, data) {
      if (data.result[0].location) {
        $("#location")[0].value = data.result[0].location
        CommutersConnectNewReport.showLocation(data.result[0].lat, data.result[0].lng);
      }
    });
  }


  //When asked to show a location for the first time, we cause it to slide
  //into focus.  Any subsequent request will simply swap the source of the
  //image.
  this.showLocation = function() {
      var isVisible = false;
      return function(lat, lng) {
          $("#previewImage").each(function(index, item) {
              if (!isVisible) {
                  $(item).show(200);
                  isVisible = true;
              }
              var latLng = lat+","+lng;
              var url = "//maps.googleapis.com/maps/api/staticmap?center="+latLng+"&markers="+latLng+"&zoom=16&size=250x250&maptype=roadmap&sensor=false"
              item.src=url;
          })
      }
  }()

}

$(document).ready(function() {
  CommutersConnectNewReport.setup();
});
